class InboxController < ApplicationController
  before_filter :login_required

  def index
    @tasks = User.find(session['user']).inbox_tasks
  end
  
  def review
  end
  
  def next_task
    project_id = sanitize_input('id')
    state      = sanitize_input('state')
    state      = 'inbox' if state == nil
    user = User.find(session['user'])
    user_projects = user.active_projects_ids.join(',')
    cond  = "user_id=#{user.id} and done=0"
    if state == 'starred'
      cond += " and star='1'"
    else
      cond += " and state='#{state}'"
    end
    if project_id != '0'
      cond += " and project_id='#{project_id}'"
    else  
      cond += " and (project_id=0 or project_id in (#{user_projects}))" if user_projects != ''
    end
    count = Task.count(:conditions=>cond) - session[:review_index]
    task  = Task.find(:first, :conditions=>cond, :order=>"id", :limit=>1, :offset=>session[:review_index])
    if !task
      render(:text=>"Great ! You have no more task to review.")
    else
      render(:partial=>"task", :locals=>{:task=>task, :count=>count})
    end  
  end
  
  def save
    state   = params[:s]
    id      = params[:id]
    begin
      t     = Task.find(id)
      if state=='done'
        t.mark_done 
      else
        t.state = state
      end  
      t.save
    rescue Exception=>e  
      render(:text=>e)
      return
    end  
    redirect_to(:action=>'next_task')
  end

  def skip
    session[:review_index] = session[:review_index].to_i + 1
    redirect_to(:action=>'next_task')
  end
  
private

  def sanitize_input(i)
    eval("#{i} = params[:#{i}]")
    if eval("#{i}") != nil
      session[eval(":review_#{i}")] = eval("#{i}")
      session[:review_index] = 0
    else
      eval("#{i} = session[:review_#{i}]")
    end
    eval("#{i}")
  end  
  
end

